<template>
  <div>
    <div class="common_form_search">
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.goodsName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.shopName"
            placeholder="请输入供应商名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.receivingName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.receivingMobile"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="短信状态">
          <el-select
            v-model="searchForm.sendStatus"
            placeholder="全部"
            clearable
          >
            <el-option label="未发送" :value="1" />
            <el-option label="已发送" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="逾期天数">
          <div class="overdue_day_input">
            <el-input
              v-model="searchForm.min"
              style="width: 80px"
              placeholder="0"
              clearable
              @input="(val) => changeNumberInput('min', val)"
            />
            <span>至</span>
            <el-input
              v-model="searchForm.max"
              style="width: 80px"
              placeholder="0"
              clearable
              @input="(val) => changeNumberInput('max', val)"
            />
          </div>
        </el-form-item>
        <el-form-item label="预计扣款日">
          <my-date-picker ref="myDatePicker" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="search()"
            >查询</el-button
          >
          <el-button size="small" @click="reset()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-divider />
    </div>
    <div class="flex flex-between-center table-top-btns">
      <div class="flex align-center">
        <h5 class="flex align-center">
          <svg-icon
            style="margin-right: 15px"
            icon-class="list"
            :size="15"
          />数据列表
        </h5>
        <div class="colorPicker">
          <el-select @change="updateColor" v-model="color" style="width: 100%" size="mini">
            <el-option
              class="colorOpts"
              v-for="(item, index) in colorConfig"
              :key="index"
              :label="item.label"
              :value="item.value"
              ><span
                class="colorRadius"
                :style="{ backgroundColor: colorMapping[item.value] }"
              ></span
              >{{ item.label }}</el-option
            >
          </el-select>
        </div>
        <el-tooltip
          class="item"
          effect="dark"
          content="一个账单一个月只能发送一次短信"
          placement="top-start"
        >
          <el-button
            v-if="$hasMethod('#batchSend')"
            size="small"
            class="add-btn svg-btn"
            @click="batchSend"
          >
            <svg-icon icon-class="batch" :size="11" />批量发送短信
          </el-button>
        </el-tooltip>
        <el-button
          v-if="$hasMethod('#export')"
          size="small"
          icon="el-icon-upload2"
          class="export-btn"
          @click="exportFile"
          >导出</el-button
        >
      </div>
      <p style="font-size: 12px; color: #000000">
        <span>逾期总数量：{{ overdueCount }}条</span>
        <!--        <span style="margin-left:20px">逾期总金额：{{ overdueAmount }}元</span>-->
      </p>
    </div>
    <div class="overdue_list">
      <el-table
        ref="multipleTable"
        :data="tableData"
        @selection-change="handleSelectionChange"
        row-key="id"
        :row-class-name="rowClass"
        border
        :tree-props="{ children: 'children' }"
      >
        <el-table-column fixed align="center" type="selection" width="55" />
        <el-table-column fixed align="center" label="订单号">
          <template slot-scope="scope">
            <span
              class="blue-font pointer"
              @click="goToOrder(scope.row.trade_no)"
              >{{ scope.row.trade_no }}</span
            >
          </template>
        </el-table-column>
        <el-table-column align="center" prop="goods_title" width="150" label="商品名称">

        </el-table-column>
        <el-table-column
          v-if="$hasMethod('#changePromoter')"
          align="center"
          label="订单来源"
          prop="source"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.name == null ? "自然流量" : scope.row.name
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="第几期">
          <template slot-scope="scope">
            <span
              >{{ scope.row.which_period }}/{{ scope.row.month_total }}</span
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="租期" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.begin_time }}/{{ scope.row.end_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="begin_time"
          label="预计扣款日"
          width="100"
        />
        <el-table-column align="center" prop="rent" label="账单金额" />
        <el-table-column align="center" prop="paid_rent" label="实付金额" />
        <el-table-column align="center" prop="no_pay" label="坏账金额" />
        <el-table-column align="center" prop="withhold_num" label="扣款次数" />
        <el-table-column align="center" prop="cert_name" label="姓名" />
        <el-table-column align="center" prop="mobile" label="手机号" />
        <el-table-column align="center" prop="realname" label="收货人" />
        <el-table-column align="center" prop="prov" label="省" />
        <el-table-column align="center" prop="city" label="市" />
        <el-table-column align="center" prop="area" label="区/县" />
        <el-table-column
          align="center"
          prop="address"
          label="收货地址"
          width="120"
        />
        <el-table-column align="center" label="订单状态" prop="statusName" />

        <el-table-column align="center" label="支付状态">
          <template slot-scope="scope">
            <span>{{
              scope.row.lease_status == 1
                ? "已支付"
                : scope.row.lease_status == 2
                ? "已退款"
                : scope.row.lease_status == 3
                ? "已买断"
                : scope.row.lease_status == 4
                ? "已逾期"
                : "未支付"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="overdue_days" label="逾期天数" />
        <el-table-column align="center" prop="sms_num" label="发送次数" />
        <el-table-column align="center" width="100" label="短信状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.send_status == 1 ? '' : 'success'">{{
              scope.row.send_status == 1 ? "未发送" : "已发送"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          prop="shopname"
          label="供应商名称"
        />
        <el-table-column fixed="right" align="center" width="190" label="操作">
          <template slot-scope="scope">
            <!--          <el-button-->
            <!--            v-if="$hasMethod('#withhold')"-->
            <!--            style="margin-right:10px"-->
            <!--            type="warning"-->
            <!--            size="mini"-->
            <!--            @click="withholdItem(scope.row.order_id,scope.row.lease_id)"-->
            <!--          >发起代扣 </el-button>-->
            <el-button
              v-if="$hasMethod('#withhold') && scope.row.is_pdf == 0"
              type="warning"
              size="mini"
              @click="letterPdf(scope.row.order_id, scope.row.lease_id)"
            >
              律师函
            </el-button>
            <el-button
              v-if="$hasMethod('#withhold') && scope.row.is_pdf == 1"
              type="info"
              size="mini"
              disabled
            >
              已下载
            </el-button>

            <el-button
              style="margin-top: 10px"
              type="primary"
              size="mini"
              @click="checkUrl(scope.row)"
              >查看报告
            </el-button>

            <el-button v-if="$hasMethod('#viewHandover')"
                       style="margin-top: 10px"
                       type="danger"
                       size="mini"
                       @click="cancelHandover(scope.row.order_id)"
            >取消移交
            </el-button>

            <el-dropdown
              v-if="$hasMethod('#viewRecord') || $hasMethod('#viewRemark')"
              @command="(command) => handleMore(command, scope.row)"
            >
              <span
                class="el-dropdown-link blue-font pointer"
                style="margin-left: 10px"
              >
                更多操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="$hasMethod('#viewRecord')" command="1"
                  >查看记录</el-dropdown-item
                >
                <el-dropdown-item v-if="$hasMethod('#viewRemark')" command="2"
                  >查看备注</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <custom-page ref="customPage" :total="total" @getList="getList" />
      <view-dialog ref="viewDialog" :view-item="selectedItem" />
      <remark-dialog
        ref="remarkDialog"
        :order-id="selectedItem.order_id"
        :which-period="selectedItem.which_period"
      />
      <letter-dialog
        ref="letterDialog"
        :letter-item="letterItem"
        @getList="getList"
      />
    </div>
  </div>
</template>

<script>
import customPage from "@/components/customPage";
import myDatePicker from "@/components/myDatePicker";
import {
  financeOverdueList,
  overdueListExport,
  manualWithholding,
  sendOverdueSms,
  orderErrorList,
  sureOrderRepayment,
  updateColor,
  updateHandOver
} from "@/api/finance";
import { lawyerLetter } from "@/api/order";
import letterDialog from "./letter";
import viewDialog from "./view";
import remarkDialog from "./remark";
export default {
  components: {
    customPage,
    myDatePicker,
    viewDialog,
    remarkDialog,
    letterDialog,
  },
  data() {
    return {
      searchForm: {
        orderNo: "",
        goodsName: "",
        shopName: "",
        receivingName: "",
        receivingMobile: "",
        sendStatus: "",
        min: "",
        max: "",
        leaseTime: "",
      },
      letterItem: {},
      tableData: [],
      total: 0,
      color: "",
      colorMapping: {
        orange: "#FF8000",
        red: "#f14949",
        zongzi: "rgb(199,161,130)",
        purple: "#a020f0",
        blue:'blue'
      },
      colorConfig: [
        /*颜色配置 */
        {
          value: "",
          label: "请选择",
        },
        {
          value: "orange",
          label: "橙色",
        },
        {
          value: "red",
          label: "红色",
        },
        {
          value: "zongzi",
          label: "粽色",
        },
        {
          value: "blue",
          label: "蓝色",
        },
        {
          value: "purple",
          label: "紫色",
        },
      ],
      overdueCount: 0,
      overdueAmount: 0,
      selectedItem: {},
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    updateColor(color){
      if(!this.judgeSelection())return;
      const list = this.$refs.multipleTable.selection;
      const ids = list.map((k) => k.order_id);
      updateColor({orderId_Json:ids,color}).then(()=>{
        this.getList();
      })
    },
    judgeSelection(){
      const list = this.$refs.multipleTable.selection;
      if (list.length === 0) {
        this.$message({
          message: "没有勾选项",
          type: "warning",
        });
        return false;
      }
      return true
      
    },
    handleSelectionChange(lists){
      let color = '';
      let colorDiff = false;
      lists.map((item)=>{
        if(color == ''){
          color = item.color
        }else {
          if(color != item.color){
            colorDiff = true 
          }
        }
      })
      if(colorDiff){
        this.color = ''
      }else{
        this.color = color;
      }
    },
    batchSend() {
      const list = this.$refs.multipleTable.selection;
      if (list.length === 0) {
        this.$message({
          message: "没有勾选项",
          type: "warning",
        });
        return;
      }
      const ids = list.map((k) => k.lease_id).join(",");
      sendOverdueSms(ids).then((res) => {
        this.getList();
      });
    },
    // 发起代扣
    withholdItem(orderId, leaseId) {
      const that = this;
      this.$confirm("您确定要发起代扣吗？", "发起代扣", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          manualWithholding({ orderId, leaseId }).then((res) => {
            setTimeout(() => {
              that.getList();
            }, 1000);
          });
        })
        .catch(() => {});
    },

    repaymentOrder(leaseId) {
      const that = this;
      this.$confirm("您确定要移至已还款列表吗？", "移至已还款列表", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          sureOrderRepayment({ leaseId }).then((res) => {
            that.$message({
              message: "操作成功",
              type: "success",
            });
            setTimeout(() => {
              that.getList();
            }, 1000);
          });
        })
        .catch(() => {});
    },
    handleMore(command, item) {
      this.selectedItem = item;
      if (command == 1) {
        // 查看记录
        this.$refs.viewDialog.dialogVisible = true;
      } else {
        // 查看备注
        this.$refs.remarkDialog.dialogVisible = true;
      }
    },
    goToOrder(orderId) {
      if (orderId) {
        this.$router.push({ name: "orderList", params: { orderId } });
      }
    },
    exportFile() {
      const pickerVal = this.$refs.myDatePicker.getVal();
      if (pickerVal == "error") {
        return;
      }
      this.searchForm.leaseTime = pickerVal;
      const params = { ...this.searchForm };
      params.overdueDay =
        params.min && params.max ? params.min + "~" + params.max : "";
      delete params.min;
      delete params.max;
      overdueListExport(params);
    },
    changeNumberInput(key, value) {
      const pattern = /^[1-9][0-9]*$/; // 正整数的正则表达式
      // 不符合正整数时
      if (!pattern.test(value)) {
        // input 框绑定的内容为空
        this.searchForm[key] = "";
      }
    },
    // 获取数据
    getList() {
      const { page, pageSize } = this.$refs.customPage;
      const params = { ...this.searchForm };
      params.overdueDay =
        params.min && params.max ? params.min + "~" + params.max : "";
      delete params.min;
      delete params.max;
      orderErrorList({
        page,
        pageSize,
        ...params,
      }).then((res) => {
        const {
          list: { data, total },
          count: { overdueCount, overdueAmount },
        } = res;
        this.tableData = data || [];
        this.total = total || 0;
        this.overdueCount = overdueCount;
        this.overdueAmount = overdueAmount;
      });
    },
    // 查询
    search() {
      const pickerVal = this.$refs.myDatePicker.getVal();
      if (pickerVal == "error") {
        return;
      }
      this.searchForm.leaseTime = pickerVal;
      this.$refs.customPage.page = 1;
      this.getList();
    },
    rowClass({row}){
      return row.color || 'white'
    },
    // 重置
    reset() {
      if (this.$refs.myDatePicker) {
        this.$refs.myDatePicker.reset();
      }
      this.searchForm = {
        orderNo: "",
        goodsName: "",
        shopName: "",
        receivingName: "",
        receivingMobile: "",
        sendStatus: "",
        min: "",
        max: "",
        leaseTime: "",
      };
      this.getList();
    },
    letterPdf(item, res) {
      //查看律师函

      lawyerLetter({ order_id: item }).then((res) => {
        this.letterItem = res;
        this.$refs.letterDialog.dialogVisible = true;
      });
    },

    checkUrl(row) {
      if (row.data_pdf_url) {
        if (row.local_url == null) {
          window.open(row.data_pdf_url);
        } else {
          let local_url = "";
          local_url =
            process.env.VUE_APP_LOCAL_URL + "storage/rick/" + row.local_url;
          window.open(local_url);
        }
      } else {
        this.$message.warning("未生成报告");
        return;
      }
    },
    cancelHandover(orderId){
      const that = this;
      console.log(111);
      this.$confirm("您确定要取消移交吗？", "取消移交", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
          .then(() => {
            updateHandOver({ orderId }).then((res) => {
              console.log(222)
              that.$message({
                message: "操作成功",
                type: "success",
              });
              setTimeout(() => {
                that.getList();
              }, 1000);
            });
          })
          .catch(() => {});
    }
  },

};
</script>

<style lang="scss" scoped>
.overdue_day_input {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  /deep/.el-input__inner {
    border: none;
  }
}
.table-top-btns{
  position: sticky;
  left: 0;
  top: 0;
  z-index: 10;
  background-color: #fff;
  padding-top: 24px;
  padding-bottom: 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #eee;
}
.goods_color_flex{
  display: flex;
  .goods_color{
    display: inline-block;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    margin-right: 8px;
  }
  .goods_title{
    display: inline-block;
    width: 110px;
  }
}
.colorPicker {
  width: 150px;
}
.colorOpts {
  display: flex;
  align-items: center;
}
.overdue_list{
  /deep/ .el-table__body .cell{
    color:#666;
  }
  /deep/ .el-table__body .orange .cell{
    color:#FF8000;
  }
  /deep/ .el-table__body .red .cell{
    color:#f14949;
  }
  /deep/ .el-table__body .zongzi .cell{
    color:rgb(199,161,130);
  }
  /deep/ .el-table__body .purple .cell{
    color:#a020f0;
  }
  /deep/ .el-table__body .blue .cell{
    color:blue;
  }
}
.common_form_search{
  /deep/ .el-divider{
    margin-bottom: 0;
  }
}
.colorRadius {
  width: 20px;
  height: 20px;
  display: inline-block;
  border-radius: 50%;
  border: 1px solid #ddd;
  margin-right: 8px;
}
</style>
